from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
import os
import subprocess
import random
import io
from pydantic import BaseModel

app = FastAPI()

# 加载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")


def remove_file(path: str):
    if os.path.exists(path):
        os.remove(path)  # 删除文件


class Params(BaseModel):
    content: str
    type: str


# 测试的POST请求
@app.post("/audio")
async def create_audio(item: Params):
    num = random.randint(1, 100000000)
    command = (
        f'edge-tts --voice {item.type} --text "{item.content}" --write-media {num}.mp3'
    )
    subprocess.run(command, stdout=subprocess.PIPE, shell=True, check=True)
    fileUrl = f"{num}.mp3"
    with open(f"{num}.mp3", "rb") as file:
        content = file.read()
    os.remove(fileUrl)
    return StreamingResponse(io.BytesIO(content), media_type="audio/mpeg")


# GET请求加载index.html文件
@app.get("/", response_class=HTMLResponse)
async def read_index(request: Request):
    with open(os.path.join("static", "index.html"), "r") as f:
        html_content = f.read()
    return HTMLResponse(content=html_content, status_code=200)


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)
